<template>
  <el-form
    ref="registerForm"
    :model="registerForm"
    :rules="rules"
    label-width="120px"
    class="registerForm sign-up-form"
  >
    <el-form-item label="用户名" prop="name">
      <el-input placeholder="输入用户名" v-model="registerForm.name" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input
        type="password"
        placeholder="输入密码"
        v-model="registerForm.password"
      />
    </el-form-item>
    <el-form-item label="确认密码" prop="confirmPassword">
      <el-input
        type="password"
        placeholder="再次输入密码"
        v-model="registerForm.confirmPassword"
      />
    </el-form-item>
    <el-form-item>
      <!-- 提交前进行校验 -->
      <el-button
        @click="handleRegister(registerForm)"
        type="primary"
        class="submit-btn"
      >
        注册
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { register } from '@/api/employee'
import { ElForm } from 'element-ui/types/form'

@Component({})
export default class registerForm extends Vue {
  registerForm = {
    name: '',
    password: '',
    confirmPassword: '',
  }
  private rules = {
    name: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 11, message: '长度应为3到11个字符', trigger: 'blur' },
    ],
    password: [
      {
        required: true,
        message: '密码不能为空',
        trigger: 'blur',
      },
      { min: 6, max: 12, message: '密码长度应为6到12个字符', trigger: 'blur' },
    ],
    confirmPassword: [
      {
        required: true,
        message: '密码不能为空',
        trigger: 'blur',
      },
      { min: 6, max: 12, message: '密码长度应为6到12个字符', trigger: 'blur' },
    ],
  }
  private handleRegister() {
    ;(this.$refs.registerForm as ElForm).validate(async (valid: boolean) => {
      if (valid) {
        if (this.registerForm.password !== this.registerForm.confirmPassword) {
          this.$message.error('两次输入的密码不一致')
        } else {
          register(this.registerForm)
            .then((response) => {
              const { code, message } = response.data
              if (code === 1) {
                this.$message.success('注册成功，请返回登录')
              } else {
                this.$message.error(message)
              }
            })
            .catch((error) => {
              console.log(error)
              this.$message.error('注册失败')
            })
        }
      } else {
        this.$message.error('表单校验失败')
        return false
      }
    })
  }
}
</script>
<style>
.el-button--primary {
  background: #3590f0;
}
.registerForm {
  margin-top: -300px !important;
  border-radius: 30px !important;
}
</style>